import React, { useRef, useState, useEffect } from 'react';
import { Spin, Form, Row, Col, Input, Empty, message } from 'antd'
import { withRouter } from 'umi';
import { useMeasure, useMount } from 'react-use';
import classNames from 'classnames';
import keyBy from 'lodash/keyBy';

import If from '@/components/If';
import { isSuccess } from '@/utils/request';
import { processService } from '@/services/salaryManage/process';
import DateFormatter from '@/components/DateFormatter';

import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import { OrganizationNameConnect } from '@/pages/SalaryManage/components/OrganizationName';

import SalaryPaySteps from './components/SalaryPaySteps';
import Context, { contextValue } from './context';
import OrganizationNameItem from './OrganizationNameItem';
import style from './index.less';

const getWidthMapper = width => {
    let widthMapper;

    // 一列最小408计算
    if (width < 816) {
        widthMapper = {
            small: 24,
            large: 24
        };
    } else if (width < 1224) {
        widthMapper = {
            small: 12,
            large: 12
        };
    } else if (width < 1624) {
        widthMapper = {
            small: 8,
            large: 8
        };
    } else {
        widthMapper = {
            small: 6,
            large: 6
        };
    }

    return widthMapper;
};

// 过滤出要显示的数据
const filterShow = item => !item.hidden;
const SalaryPaySettingProcess = ({ form, formValueMap, dataSource, location }) => {
    const [loading, setLoading] = useState(false);
    const [ref, { width }] = useMeasure();
    const widthMapper = getWidthMapper(width);

    const [pageModel, setPageModel] = useState(formValueMap?.salaryGrantApplyModel || {});

    console.groupCollapsed('%cSalarySetGrantApply套件信息', 'color: #7e2065');
    console.log('formValueMap:', formValueMap);
    console.log('dataSource:', dataSource);
    console.log('location:', location);
    console.groupEnd();

    const childConfig = dataSource?.children?.length > 0 ? dataSource.children : [];
    const childrenConfigMap = keyBy(childConfig, 'formId');
    const summaryConfig = childrenConfigMap.summary;
    const organizationNameConfig = childrenConfigMap.organizationName;
    const uploadConfig = childrenConfigMap.OssUploadFiles;

    const { getFieldDecorator } = form;
    const { beforeSetProcessVOs: leftList = [] } = pageModel;
    const { afterSetProcessVOs: rightList = [] } = pageModel;
    const showLeftList = leftList.filter(filterShow);
    const showRightList = rightList.filter(filterShow);
    const leftRef = useRef();
    const rightRef = useRef();

    contextValue.leftList = showLeftList;
    contextValue.rightList = showRightList;
    const [contextState, setContextState] = useState(contextValue);
    const context = { contextState, setContextState };

    const isApply = location.query?.apply === '1';
    // 由于在申请界面或审批详情界面限定了90%的宽度(表单设计页没有限定)，而且我们要100%，所在增加了负值的marginRight
    const extraRight = isApply || formValueMap;
    // 如果流程附件配置为只读时，后台不会返回配置信息，就无需显示
    if (uploadConfig) {
        uploadConfig.uploadProps.disabled = uploadConfig.options.disabled;
    }

    const inputOnchange = event => setPageModel({ ...pageModel, remark: event.target.value });

    useMount(() => {
        const scrollFn = () => {
            if (leftRef.current.scrollTop !== rightRef.current.scrollTop) {
                rightRef.current.scrollTop = leftRef.current.scrollTop;
            }
        };
        leftRef.current.addEventListener('scroll', scrollFn);

        return () => {
            leftRef.current.removeEventListener('scroll', scrollFn);
        };
    });

    useMount(async () => {
        // 如果是发起申请的界面
        if (isApply) {
            setLoading(true);
            try {
                const organizationCode = location.query?.organizationCode;
                const response = await processService.querySalaryPaySettingProcessModel(organizationCode);
                setLoading(false);
                if (isSuccess(response)) {
                    setPageModel(response.data);
                    console.log(response.data);
                } else {
                    message.error(response.msg);
                }
            } catch (e) {
                setLoading(false)
            }
        }
    });

    useEffect(
        () => {
            if (formValueMap?.salaryGrantApplyModel) {
                setPageModel(formValueMap?.salaryGrantApplyModel);
            }
        },
        [formValueMap]
    );

    return (
        <Spin spinning={loading}>
            <div className={classNames(style.SalaryPaySettingProcess, { [style.extraRight]: extraRight })}>
                {getFieldDecorator('salaryGrantApplyModel', {
                    initialValue: pageModel
                })(<Input type="hidden" />)}

                {/* 行政机构 */}
                <OrganizationNameItem
                    form={form}
                    formValueMap={formValueMap}
                    organizationNameConfig={organizationNameConfig}
                    organizationCode={pageModel?.organizationCode}
                />

                {/* 流程名称 */}
                {
                    summaryConfig
                        ? <Form.Item
                            label={summaryConfig.label}
                            key={summaryConfig.formId}
                            style={{ display: summaryConfig?.inRenderDom === false ? 'none' : 'block' }}
                        >
                            {getFieldDecorator(summaryConfig?.formId, {
                                rules: summaryConfig?.rules,
                                initialValue: formValueMap?.[summaryConfig.formId]
                                    ?? summaryConfig?.options?.initialValue
                            })(<AutoRenderComponent form={form} config={summaryConfig} />)}
                        </Form.Item>
                        : null
                }

                <div ref={ref} style={{ maxWidth: 1224 }} className={style.ml8}>
                    <If condition={pageModel?.organizationCode || formValueMap?.applicationNo }>
                        <Row>
                            <If condition={pageModel?.organizationCode}>
                                <Col span={widthMapper.small}>
                                    <Form.Item label="行政机构：" className={classNames(style.mb0)}>
                                        <OrganizationNameConnect organizationCode={pageModel?.organizationCode} />
                                    </Form.Item>
                                </Col>
                            </If>
                            <If condition={formValueMap?.applicationNo}>
                                <Col span={widthMapper.small}>
                                    <Form.Item label="申请编号：" className={classNames(style.mb0)}>
                                        {formValueMap?.applicationNo}
                                    </Form.Item>
                                </Col>
                            </If>
                        </Row>
                    </If>

                    <Row>
                        <Col span={widthMapper.small}>
                            <Form.Item label="申请人员：" className={classNames(style.mb0)}>
                                {pageModel.approver}
                            </Form.Item>
                        </Col>
                        <Col span={widthMapper.small}>
                            <Form.Item label="所在部门：" className={classNames(style.mb0)}>
                                {pageModel.dept}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={widthMapper.small}>
                            <Form.Item label="申请日期：" className={classNames(style.mb0)}>
                                <DateFormatter value={pageModel.approveStartTime} pattern="YYYY-MM-DD" />
                            </Form.Item>
                        </Col>
                        <Col span={widthMapper.large}>
                            <Form.Item label="重要提示：" className={classNames(style.mb0)}>
                                {!isApply
                                    ? <span className={style.info} ><EmptyPlaceHolder value={pageModel.remark} /></span>
                                    : <Input
                                        maxLength={200}
                                        onChange={inputOnchange}
                                        disabled={!isApply}
                                        value={pageModel.remark}
                                    />}

                            </Form.Item>
                        </Col>
                    </Row>
                </div>

                <Context.Provider value={context}>
                    <Row type="flex" gutter={32} className="compare">
                        <Col className="compare-item">
                            <h6 className="compare-item-title">变更前</h6>
                            <div ref={leftRef} className="compare-item-body">
                                <If condition={showLeftList?.length > 0}>
                                    <SalaryPaySteps prefix="left" data={showLeftList} compareData={showRightList} />
                                </If>
                                <If condition={!showLeftList?.length}>
                                    <Empty
                                        description="暂无数据"
                                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                                        style={{ marginLeft: '20px' }}
                                    />
                                </If>
                            </div>
                        </Col>
                        <Col className="compare-item">
                            <h6 className="compare-item-title">变更后</h6>
                            <div ref={rightRef} className="compare-item-body">
                                <If condition={showRightList?.length > 0}>
                                    <SalaryPaySteps prefix="right" data={showRightList} compareData={showLeftList} />
                                </If>
                                <If condition={!showRightList?.length}>
                                    <Empty
                                        description="暂无数据"
                                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                                        style={{ marginLeft: '20px' }}
                                    />
                                </If>
                            </div>
                        </Col>
                    </Row>
                </Context.Provider>

                {
                    uploadConfig
                        ? <Row>
                            <Form.Item label="附件：" className={classNames(style.mb0, style.flex)}>
                                {getFieldDecorator(uploadConfig?.formId, {
                                    rules: uploadConfig?.rules,
                                    initialValue: formValueMap?.[uploadConfig.formId] ?? uploadConfig.initialValue
                                })(<AutoRenderComponent form={form} config={uploadConfig} />)}
                            </Form.Item>
                        </Row>
                        : null
                }
            </div>
        </Spin>
    );
};

export default withRouter(React.memo(SalaryPaySettingProcess));
